<template>
    <div style="background-color: #f1f4f6;width: 100%;height: 89.5vh;">
        <div class="chat-page" style="height: 70vh;width: 60vw;position: absolute;
    top: 50%;left: 50%;
    transform: translate(-50%,-50%);
   
    "
        >
            <div class="chat-sidebar" style="border-radius: 15px 0 0 15px;padding: 0;overflow-y: hidden;background-image: linear-gradient(to bottom, rgba(243,120,82,0.22),rgba(201,155,123,0.17));">
                <!-- 添加搜索框 -->
                <el-input @input="guolv" v-model="searchQuery" placeholder="搜索对话..." style="width: 100%; padding: 10px;"></el-input>
                
                <el-scrollbar style="overflow-y: auto;height: 814px;">
                    <!-- 过滤后的聊天对象列表 -->
                    <div v-for="chat in chats" :key="chat.id" class="chat-item" @click="selectChat(chat)" v-show="chat.isShow">
                        <el-avatar :src="chat.avatar" class="avatar"></el-avatar>
                        <div class="chat-info">
                            <h3 style="color: black">{{ chat.name }}</h3>
                            <p>{{ chat.lastMessage }}</p>
                        </div>
                    </div>
                </el-scrollbar>
            </div>
            
            <div class="chat-window" >
                <div class="chat-header" style="background-color: #fffdf8;text-align: center;border-radius: 0 15px 0 0;">
                    <h3 style="color: black">{{ currentChat.name }}</h3>
                    <span v-if="showUnline" style="color: #888888">对方暂时不在线~</span>
                </div>
                <el-scrollbar class="chat-messages" ref="messageScrollbar" :style="{'border-radius':showRadius?'0 0 15px 0':'0 0 0 0'}">
                    <div v-for="message in currentChat.messages"  :class="messageClass(message)" >
                        <div class="message-content" style="position: relative;margin-bottom: 25px;margin-top: 30px">
                            <div class="message-time" style="position: absolute;left: 300px;top: -30px;opacity: .9;color: #888888">{{ message.createTime }}</div>
                            <el-avatar :src="message.fromId==userId?user.avatar:currentChat.avatar" class="message-avatar"></el-avatar>
                            <div class="message-text">{{ message.message }}</div>
                        </div>
                    </div>
                </el-scrollbar>
                <div class="chat-input" v-show="showInput" style="border-radius: 0 0 15px 0;">
                    <el-input
                        class="marquee-input"
                        v-model="newMessage"
                        placeholder="请输入你要发送的消息~"
                        @keyup.enter="sendMessage"
                        clearable
                        size="small"
                        ref="focuss">
                    </el-input>
                    <el-button @click="sendMessage" type="primary" style="position: absolute;right: 30px;bottom: 19px;  width: 50px;height: 30px;">发送</el-button>
                </div>
            </div>
        </div>
    </div>
    
</template>

<script setup>
import { nextTick, onMounted, ref } from "vue";
import {ElMessage} from "element-plus";
import axios from "axios";

const chats = ref([
    //示例
    // {
    //     id: 10666,
    //     name: 'Bob',
    //     avatar: '2.png',
    //     messages: [
    //     ],
    //     lastMessage: 'Let\'s catch up later!',
    //      isShow:true;
    // }
]);
const showRadius=ref(true)
const showUnline=ref(false)
//输入框默认不显示 之后进入页面默认选中就可以取消这行代码
const showInput=ref(false)
const currentChat = ref({});
const newMessage = ref('');
const messageScrollbar = ref(null);
const focuss=ref(null)
let userId;
let shopId
let shopNickname;
let wsUrl;
let ws=null;

// 默认选中第一个聊天
onMounted(() => {
    userId=new URLSearchParams(window.location.search).get('uid');
    shopId=new URLSearchParams(window.location.search).get('sid');
    shopNickname=new URLSearchParams(window.location.search).get('snick');
    
    //去后端查询shop的个人信息 添加到 chats
    //如果有shopId默认选中  如果没有 就不做操作
    //这里得等待 获取后端用户数据 以及websocket连接成功之后执行
    axios.get(BASE_URL+'/v1/msg/selectSayed?id='+userId)
        .then((res)=>{
            if (res.data.code===2002){
                let data=res.data.data;
                for (let i=0;i<data.length;i++){
                    chats.value.push({id:data[i].id,name:data[i].nickname,messages: [],avatar:BASE_URL+"/"+data[i].img,lastMessage: '',newMessages: false,isShow:true})
                }
                console.log(chats.value)
            }
        })
    
    
    
    setTimeout(()=>{
        if (shopId!=undefined){
            for (let i=0;i<chats.value.length;i++){
                if (chats.value[i].id==shopId){
                    //如果有商家ID 则定位到当前商家 并return
                    currentChat.value=chats.value[i]
                    return;
                }
            }
            //如果没有 则 添加到chats 即可向对方发送消息    这里的shopId 以及 shopNickname都要 前一个页面传递过来
            chats.value.push({id:shopId,name: shopNickname,messages:[],newMessages: false,isShow:true});
            currentChat.value=chats.value[chats.value.length-1];
            showRadius.value=false;
            showInput.value=true;
        }
    },500)
    
    wsUrl ='ws://localhost:8080/chat/'+userId;
    ws=new WebSocket(wsUrl);
    
    ws.onopen=(e)=>{
        ElMessage.success("WebSocket连接成功!")
        //连接成功后 等待上一个请求返回 对话对象 再使用对话对象去获取 消息记录 所以延迟300毫秒
        setTimeout(()=>{
            for (let i=0;i<chats.value.length;i++){
                ws.send(userId+'-'+chats.value[i].id+":");
            }
        },300)
    }
    
    ws.onmessage=(e)=>{
        console.log(666)
        if (/^\[\{.*\}\]$/.test(e.data)){
            let dataArr=JSON.parse(e.data);
            let id=0;
            if (dataArr[0].fromId==userId){
                id=dataArr[0].toId;
            }else {
                id=dataArr[0].fromId;
            }
            console.log(id)
            for (let i=0;i<chats.value.length;i++){
                if (chats.value[i].id==id){
                    chats.value[i].messages=dataArr;
                    chats.value[i].lastMessage=dataArr[dataArr.length-1].message;
                }
            }
        }else if (e.data==="对方用户不在线！"){
            showUnline.value=true;
        } else {
            let message=e.data;
            let gan=message.indexOf("-");
            let mao=message.indexOf(":")
            let fromId=message.substring(0,gan)
            message=message.substring(mao+1);
            for (let i=0;i<chats.value.length;i++){
                if (chats.value[i].id==fromId){
                    // 头像暂时未添加
                    chats.value[i].messages.push({message: message,fromId: fromId,avatar: ''})
                    chats.value[i].lastMessage=message;
                }
            }
        }
        setTimeout(() => {
            const scrollElement = messageScrollbar.value.wrapRef;
            if (scrollElement) {
                scrollElement.scrollTop = scrollElement.scrollHeight; // 滚动到最底部
            }
        }, 50); // 延迟 50 毫秒或更少
    }
    ws.onclose=()=>{
        ElMessage.success("已断开WebSocket连接！")
    }
    
    
});


const selectChat =  (chat) => {
    showInput.value=true;
    currentChat.value = chat;
    showRadius.value=false;
    showUnline.value=false;
    //新建一个计时器 目的在等待DOM更新完成 执行该代码
    setTimeout(() => {
        const scrollElement = messageScrollbar.value.wrapRef;
        if (scrollElement) {
            scrollElement.scrollTop = scrollElement.scrollHeight; // 滚动到最底部
        }
        focuss.value.focus();
    }, 50); // 延迟 50 毫秒或更少
    // for (let i=0;i<queryed.length;i++){
    //     if (queryed[i]===chat){
    //         return;
    //     }
    // }
    // ws.send(userId+'-'+chat.id+":");
    // queryed.push(chat);
};

const messageClass = (message) => {
    return message.fromId == userId ? 'message-right' : 'message-left';
};

const sendMessage = () => {
    if (newMessage.value.trim()) {
        if (newMessage.value.trim()==="对方用户不在线！"){
            ElMessage.warning("不允许发送\"对方用户不在线！🤦‍\"");
            newMessage.value='';
            return;
        }
        // 获取当前时间
        const date = new Date();
// 获取年、月、日、时、分、秒
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        const seconds = String(date.getSeconds()).padStart(2, '0');

// 格式化时间
        const formattedDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        
        ws.send(userId+"-"+currentChat.value.id+":"+newMessage.value);
        currentChat.value.lastMessage=newMessage.value;
        currentChat.value.messages.push({
            message: newMessage.value,
            avatar: 'userAvatar', // 假设是用户的头像
            fromId: userId,
            createTime:formattedDate
        });
        newMessage.value = '';
        setTimeout(() => {
            const scrollElement = messageScrollbar.value.wrapRef;
            if (scrollElement) {
                scrollElement.scrollTop = scrollElement.scrollHeight; // 滚动到最底部
            }
        }, 50); // 延迟 50 毫秒或更少
    }else {
        ElMessage.info("发送消息不可以为空哦😘")
    }
};

const searchQuery = ref(''); // 搜索关键词
const guolv=()=>{
    for (let i=0;i<chats.value.length;i++){
        if (chats.value[i].name.includes(searchQuery.value)){
            chats.value[i].isShow=true;
        }else {
            chats.value[i].isShow=false;
        }
    }
}

//获取localstorage的user     img2.png 为后端静态资源文件夹的图片
let user={avatar:BASE_URL+"/img2.png"}
localStorage.setItem("user",JSON.stringify(user))
user=JSON.parse(localStorage.getItem("user"))
console.log(user.avatar)



</script>

<style scoped>
/* 同原样式 */
.chat-page {
    display: flex;
    height: 100vh;
    font-family: 'Arial', sans-serif;
}

.chat-sidebar {
    width: 300px;
    border-right: 1px solid #dcdcdc;
    background-color: #f5f5f5;
    padding: 10px;
    overflow-y: auto;
}

.chat-item {
    display: flex;
    padding: 10px;
    cursor: pointer;
    align-items: center;
    transition: background-color 0.2s;
}

.chat-item:hover {
    background-color: #eaeaea;
}

.avatar {
    width: 50px;
    height: 50px;
    border-radius: 50%;
    margin-right: 15px;
}

.chat-info h3 {
    margin: 0;
    font-size: 16px;
    font-weight: bold;
}

.chat-info p {
    margin: 0;
    color: #888;
    font-size: 14px;
}

.chat-window {
    flex: 1;
    display: flex;
    flex-direction: column;
}

.chat-header {
    padding: 15px;
    background-color: #eee;
    border-bottom: 1px solid #ddd;
}

.chat-messages {
    flex: 1;
    padding: 15px;
    background-color: #fafafa;
    overflow-y: auto;
}

.message-content {
    display: flex;
    margin-bottom: 15px;
}

.message-avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    margin-right: 10px;
}

.message-text {
    padding: 10px;
    background-color: #fff;
    border-radius: 5px;
    max-width: 60%;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.message-left .message-text {
    background-color: #f0f0f0;
    color: black;
}

.message-right {
    justify-content: flex-end;
}

.message-right .message-text {
    background-color: #0084ff;
    justify-content: flex-end;
    color: #fff;
}

.chat-input {
    padding: 10px;
    border-top: 1px solid #ddd;
    background-color: #f9f9f9;
}






.marquee-input {
    
    height: 50px;
    font-size: 18px;
}





</style>
